package com.yimixian.app.util;

import android.text.TextUtils;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * Created by Administrator on 2016/3/24.
 */
public class IOUtil {
  public static String objectToString(Object obj){
    if (obj == null) {
      return "";
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
    ObjectOutputStream oos = null;
    try {
      oos = new ObjectOutputStream(baos);
      oos.writeObject(obj);

    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      if (oos != null) {
        try {
          oos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return new String(Base64.encodeBase64(baos.toByteArray()));
  }

  public static Object stringToObject(String wordBase64){
    Object obj = null;
    if (TextUtils.isEmpty(wordBase64)) {
        return null;
    }
    byte[] base64Bytes = Base64.decodeBase64(wordBase64.getBytes());
    ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
    ObjectInputStream ois = null;
    try {
      ois = new ObjectInputStream(bais);
      obj = ois.readObject();
    } catch (StreamCorruptedException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }finally {
      if (ois != null) {
        try {
          ois.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return obj;
  }
}
